#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<vector>
#include<string>
#include<stdio.h>
#include<iostream>

using namespace std;
using namespace cv;

int main(int argc, char** argv){

    printf("read timestampes: %s \n" , argv[1]);    //时间戳文件路径
    std::string timeStampesPath = argv[1];
    std::FILE * file;
    std::cout << timeStampesPath  << endl;
    file = std::fopen((timeStampesPath ).c_str(),"r");
    if(file == NULL){
        printf("cannot find file : %s \n" , timeStampesPath.c_str());
        return 0;
    }
    std::vector<long> imageTimeList;
    long nanosec;
    //char string_Temp[60];
    // for (int i = 0 ; i < 1 ; i++){
    //     fscanf(file , "%s" , &string_Temp);
    // }
    int index = 0;
    while(fscanf(file , "%ld" , &nanosec ) != EOF){
        //cout << "reading" <<  index <<  endl;
        index++;
        imageTimeList.push_back(nanosec);
    }
    std::fclose(file);
    std::cout << imageTimeList.size() << endl; 

    std::cout << argv[2] << std::endl;          //视频路径
    VideoCapture capture;                  
    capture.open(argv[2]);
    if (!capture.isOpened()){
        printf("could not read video %s" , argv[2]);
        return -1;
    }
    int frameRate = static_cast<int>(capture.get(CV_CAP_PROP_FPS));
    int totalFrames = static_cast<int>(capture.get(CV_CAP_PROP_FRAME_COUNT));
    int width = static_cast<int>(capture.get(CV_CAP_PROP_FRAME_WIDTH));
    int height = static_cast<int>(capture.get(CV_CAP_PROP_FRAME_HEIGHT));
    cout << "视频宽度=" << width << endl;
    cout << "视频高度=" << height << endl;
    cout << "视频总帧数=" << totalFrames << endl;
    cout << "帧率=" << frameRate << endl;
    int j = 0;
     index = 0;
     int timeStame = 0;
     int t ;
     int fps;
    Mat frame;
    while(1){
        t = (double)cv::getTickCount();
        timeStame += 1;
        capture.set(CAP_PROP_POS_FRAMES , timeStame);
        capture .read( frame);
        t = ((double)cv::getTickCount() - t) / cv::getTickFrequency();
        fps = 1.0 / t;
        //cout << "帧数是： " << fps << endl;
        resize(frame , frame , Size(1280,480));
        Mat leftImage , rightImage;
        leftImage = frame(Rect(0,0,frame.size().width / 2 , frame.size().height));
        rightImage = frame(Rect(frame.size().width / 2 , 0 , frame.size().width / 2 , frame.size().height));
        string leftImageName ="/home/junjun/hyl/datasets/leftImage/" +  std::to_string(imageTimeList[j]) + ".png";
        string rightImageName ="/home/junjun/hyl/datasets/rightImage/" +  std::to_string(imageTimeList[j]) + ".png";
        // imshow("leftImage" , leftImage);
        // imshow("rightImage" , rightImage);
        imwrite(leftImageName , leftImage);
        imwrite(rightImageName , rightImage);
        j ++;
        waitKey(1);
        std::cout << "Saveing :" << index ++<< " Image" << endl;
        if (frame.empty()){
            break;
        }
    }
    return 0;
}